input1 = [[1,2],[3,4]]
r1 = 1, c1 = 4
output1 = [[1,2,3,4]]
// Explanation:The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
input2 = [[1,2],[3,4]]
r2 = 2, c2 = 4
output2= [[1,2],[3,4]]
// Explanation:There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
為了保留原始陣列,我用一個變數去接收傳入陣列,設定一個 while ,如果有第二個子陣列就繼續執行,測試就把傳出的陣列與比較用的陣列都轉成字串進行比較
input1 = [[1,2],[3,4]]
r1 = 1, c1 = 4
output1 = [[1,2,3,4]]
input2 = [[1,2],[3,4]]
r2 = 2, c2 = 4
output2= [[1,2],[3,4]]
function reshape(ary,r,c){
let a = ary
while(a[1]){
a[0] = a[0].concat(a.pop())
}
if (r*c == a[0].length){
return a
}else{
return ary.sort((x,y)=>{return x-y})
}
}
function expect(a,b){
console.log( JSON.stringify(a) == JSON.stringify(b) )
}
expect(reshape(input1,r1,c1),output1)
expect(reshape(input2,r2,c2),output2)
迴圈內就把子陣列合併,把第一個子陣列與最後一個子陣列合併,合併後比較元素數量是否與題目給的 r * c 吻合,如果符合就回傳處理過的一維陣列,反之回傳原始陣列
function reshape(ary,r,c){
let a = ary
while(a[1]){
a[0] = a[0].concat(a.pop())
}
if (r*c == a[0].length){
return a
}else{
return ary
}
}
function expect(a,b){
console.log( JSON.stringify(a) == JSON.stringify(b) )
}
expect(reshape(input1,r1,c1),output1)
expect(reshape(input2,r2,c2),output2)
這時候發現,a 與 ary 都指向同一個值,改變 a 的話, ary 也會跟著變動,為了解決這個問題,我先把 ary 轉成 Json格式再指派給 a, 再把 ary 轉回陣列,這樣就能讓 a 與 ary 指向不同的位置
function reshape(ary,r,c){
let a = JSON.stringify(ary)
a = JSON.parse(a)
while(a[1]){
a[0] = a[0].concat(a.pop())
}
if (r*c == a[0].length){
return a
}else{
return ary.sort( (x,y) => {return x-y} )
}
}
function expect(a,b){
console.log( JSON.stringify(a) == JSON.stringify(b) )
}
expect(reshape(input1,r1,c1),output1)
expect(reshape(input2,r2,c2),output2)
今天到此為止,有任何問題請在下方留言或透過email、GitHub聯絡我,感謝閱讀
Daily kitty